/*
 * TrustDictator.java
 *
 * Created on Aug 31, 2009, 11:32:42 PM
 */

package game;

import main.Runner;
import java.util.ArrayList;
import java.util.Random;

/**
 * Works exactly like the Dictator game, only the endowments are the same as
 * the amounts received while playing Trust as player 2.
 *
 * @author Justin
 */
public class TrustDictator extends Game {
	/** Holds information on what the Trust-Dictator game will be like, which
	 * we feed to Dictator.
	 */
	ArrayList<GameInfo> gameInfoList;

	/** The Trust log file. */
	final String TRUST_LOG = "Trust_log.csv";

	/** The main log file. */
	final String MAIN_LOG = "Log.txt";

	/** The contents of the Trust log file. */
	ArrayList<ArrayList<String>> trustData;

	/** The contents of the main log file. */
	ArrayList<ArrayList<String>> mainLogData;

	// Trust file CSV columns constants.
	final int CSV_SUBJECT = 0;
	final int CSV_PLAYER = 1;
	final int CSV_KEY = 3;
	final int CSV_VALUE = 4;

	// Main log CSV columns constants.
	final int CSV_PARAMS = 2;
	final int CSV_REPSTOT = 4;

	/** What number the "key" value of the log file should be that maps to how
	 * much money p2 received from p1 in the Trust game. */
	final int KEY_RECEIVE = 4;

    /** Creates new form TrustDictator */
    public TrustDictator() {
        initComponents();
    }

	public TrustDictator (String tdParams, int currentRep) {
		super();

		String paramPart[] = tdParams.split (",");
		int reps = Integer.parseInt (paramPart[1]);

		getEndowments();

		// Trust hasn't been played yet, or the player never not nonzero values
		// while playing Trust player 2.
		if (gameInfoList.size() > 0) {
			for (int i=0; i<gameInfoList.size(); i++) {
				System.err.println ("[DEBUG]: running Dictator " + i);
				currGame = "Trust-Dictator";
				String dParams = "Trust-Dictator," + reps + ","
					+ gameInfoList.get(i).endowment + ","
					+ gameInfoList.get(i).increment;
				Runner.runDictatorPlayer1(dParams, currentRep);
			}
		}
	}

	/**
	 * Reads the log files to see if we've played Trust before. If so, then it
	 * grabs the amount of money that the player received, if that amount was
	 * greater than 0.
	 */
	private void getEndowments() {
		gameInfoList = new ArrayList<GameInfo>();
		
		// Read increments and multiplier from main game log.
		mainLogData = readCSVFile ("logs/"+MAIN_LOG);

		for (int i=1; i<mainLogData.size(); i++) {
			ArrayList<String> row = mainLogData.get(i);
			String subject = row.get(CSV_SUBJECT);
			String playerType = row.get(CSV_PLAYER);
			int repsTot = Integer.parseInt(row.get(CSV_REPSTOT));
			String tParams = row.get(CSV_PARAMS);
			String paramPart[] = tParams.split (",");
			String currentName = paramPart[0];

			double increment = 0;
			double multiplier = 0;
			if (currentName.equals("Trust")) {
				increment = Double.parseDouble (paramPart[3]);
				multiplier = Double.parseDouble (paramPart[4]);
			}

			if (subject.equals(playerId) && playerType.equals("2"))
				for (int j=0; j<repsTot; j++)
					gameInfoList.add(new GameInfo (multiplier, increment, 0));
		}

		// Read endowments from Trust player 2 games.
		trustData = readCSVFile ("logs/"+TRUST_LOG);

		int giListInd = 0; // Where in the game info list we're currently at.
		for (int i=1; i<trustData.size(); i++) {
			ArrayList<String> row = trustData.get(i);
			String subject = row.get(CSV_SUBJECT);
			String playerType = row.get(CSV_PLAYER);
			int key = -1;
			if (row.get(CSV_KEY).equals("TimeOut") == false)
				key = Integer.parseInt (row.get(CSV_KEY));
			double value = -1;
			if (row.get(CSV_VALUE).equals("TimeOut") == false)
				value = Double.parseDouble(row.get(CSV_VALUE).substring(1));

			if (subject.equals(playerId) && playerType.equals("2")
				&& key == 4) {
				gameInfoList.get(giListInd).endowment =
					gameInfoList.get(giListInd).multiplier * value;
				giListInd++;
			}
		}

		// Search for any size 0 endowments, and remove them. Also remove the
		// corresponding element from the increments list.
		for (int i=gameInfoList.size()-1; i>=0; i--)
			if (gameInfoList.get(i).endowment == 0)
				gameInfoList.remove(i);

		// Randomly permute the list.
		Random random = new Random();
		for (int i=gameInfoList.size()-1; i>=0; i--) {
			int randInd = random.nextInt(i+1);
			GameInfo swapTemp = gameInfoList.get(randInd);
			gameInfoList.set(randInd, gameInfoList.get(i));
			gameInfoList.set(i, swapTemp);
		}
	}

	/**
	 * Holds together what the multiplier, increment, and endowment should be
	 * for the Trust-Dictator game.
	 */
	class GameInfo {
		public double multiplier;
		public double increment;
		public double endowment;
		
		public GameInfo(double multiplier, double increment, double endowment) {
			this.multiplier = multiplier;
			this.increment = increment;
			this.endowment = endowment;
		}
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        /*java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TrustDictator().setVisible(true);
            }
        });*/
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

}
